package cn.fl.product.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.*;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.prjsteprebate.condition.PrjStepRebateFeeQC;
import cn.fl.prjsteprebate.dto.PrjStepRebateFeeDTO;
import cn.fl.prjsteprebate.service.IPrjStepRebateApiService;
import cn.fl.prjsteprebate.transform.PrjStepRebateFeeVOTransform;
import cn.fl.prjsteprebate.vo.PrjStepRebateFeeVO;
import cn.fl.product.service.ISplInfoService;
import cn.fl.product.service.ISplStepRebatesService;
import cn.fl.product.transform.SplStepRebatesVOTransform;
import cn.fl.product.vo.SplInfoVO;
import cn.fl.product.vo.SplStepRebatesVO;
import cn.fl.product.vo.StepRebatesDetailVO;
import cn.fl.project.condition.PrjPrdBscInfoQueryCondition;
import cn.fl.project.service.IProjectApiService;
import cn.fl.ref.fncprjbscinfo.util.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.grpcfg.api.ISplGrpPrjBizViewApiService;
import fl.spl.facade.grpcfg.condition.SplGrpPrjBizViewQC;
import fl.spl.facade.grpcfg.dto.SplGrpPrjBizViewDTO;
import fl.spl.facade.spl.condition.SplInfoQueryCondition;
import fl.spl.facade.splrate.api.ISplRateRelInfoQueryApiService;
import fl.spl.facade.splrate.condition.SplRateRelInfoQC;
import fl.spl.facade.splrate.constant.SplRateRelInfoConstant;
import fl.spl.facade.splrate.dto.SplRateRelInfoDTO;
import fl.spl.facade.splrebates.condition.SplStepRebatesInfoQC;
import fl.spl.facade.splrebates.dto.SplStepRebatesInfoDTO;
import fl.spl.facade.store.api.ISplPropInfoApiService;
import fl.spl.facade.store.condition.SplPropInfoQueryCondition;
import fl.spl.facade.store.dto.SplPropInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/spl/rebates")
public class SplStepRebatesController {

    //供应商服务
    @Autowired
    private ISplInfoService splInfoService ;

    //供应商星级信息api服务
    @Autowired
    private ISplRateRelInfoQueryApiService splRateRelInfoQueryApiService ;
    //数据字典api服务
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService ;

    @Autowired
    private ISplStepRebatesService splStepRebatesService ;

    @Autowired
    private ISplGrpPrjBizViewApiService splGrpPrjBizViewApiService ;
    @Autowired
    private IProjectApiService projectApiService ;

    @Autowired
    private IPrjStepRebateApiService prjStepRebateApiService ;

    @Autowired
    private ISplPropInfoApiService splPropInfoApiService;

    @RequestMapping(value = "/toSplListPage.do",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView toSplListPage(HttpServletRequest request, HttpServletResponse response){
        ModelAndView view = new ModelAndView("product/splStepRebates/splInfoListPage");
        List<KeyValueVO> searchBuOrgList = this.splInfoService.searchBuOrgCdList();
        view.addObject("searchBuOrgList", searchBuOrgList);
        return view ;
    }

    @RequestMapping(value = "/initSplList.do",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object initSplList(HttpServletRequest request, HttpServletResponse response){
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String splNm = request.getParameter("splNm");
        String splAttrCd = request.getParameter("splAttrCd");
        String rgnProvCd = request.getParameter("rgnProvCd");
        String rgnCityCd = request.getParameter("rgnCityCd");
        String isBlackList = request.getParameter("isBlackList");
        String loanTmStarStr = request.getParameter("loanTmStar");
        String loanTmEndStr = request.getParameter("loanTmEnd");
        List<Long> splIds = null ;
        Map<Long,Long> splIdByAmtCountMap = new HashMap<>();
        try {
            if(StringUtils.isNotEmpty(loanTmStarStr) && StringUtils.isNotEmpty(loanTmEndStr)){
                Date loanTmStar = DateUtils.formatStringToDate(loanTmStarStr,DateUtils.YYYY_MM_DD);
                Date loanTmEnd = DateUtils.formatStringToDate(loanTmEndStr,DateUtils.YYYY_MM_DD);
                if(loanTmStar.after(loanTmEnd)){
                    throw new BaseException(BaseExceptionConstant.COMMON_0001,"放款时间有误！");
                }
                if(loanTmEnd.after(DateUtils.getDateAddDate(loanTmStar,DateUtils.MONTH,12))){
                    throw new BaseException(BaseExceptionConstant.COMMON_0001,"放款时间范围最大值为12个月！");
                }
                SplGrpPrjBizViewQC viewQC = new SplGrpPrjBizViewQC();
                viewQC.setActPayTmStar(DateUtils.formatDateToString(loanTmStar,DateUtils.YYYY_MM_DD));
                viewQC.setActPayTmEnd(DateUtils.formatDateToString(loanTmEnd,DateUtils.YYYY_MM_DD));
                List<SplGrpPrjBizViewDTO> viewDTOS = this.splGrpPrjBizViewApiService.searchSplIdAndCountAtmByTm(viewQC);
                if(CollectionUtils.isNotEmpty(viewDTOS)){
                    splIds= new ArrayList<>();
                    for (SplGrpPrjBizViewDTO viewDTO:viewDTOS) {
                        splIds.add(viewDTO.getSplId());
                        splIdByAmtCountMap.put(viewDTO.getSplId(),viewDTO.getAmtCount());
                    }
                }
            }
        }catch (BaseException be){
            BaseLogUtils.newWebLogger("查询放款信息失败").setLogOperType(LogOperEnum.RESP)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .error(BaseExceptionConstant.INTERFACE_0102);
        }catch (Exception ex){
            BaseLogUtils.newWebLogger("查询放款信息失败").setLogOperType(LogOperEnum.RESP)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .error(BaseExceptionConstant.INTERFACE_0102);
        }


        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        SplInfoQueryCondition qc = new SplInfoQueryCondition();
        qc.setIsDel(BaseConstant.IS_YESNO_NO);
        if (StringUtils.isNotBlank(splNm)) {
            qc.setSplNm(splNm);
        }
        if (StringUtils.isNotBlank(rgnProvCd)) {
            qc.setRgnPrCd(rgnProvCd);
        }
        if (StringUtils.isNotBlank(rgnCityCd)) {
            qc.setRgnCyCd(rgnCityCd);
        }
        if(StringUtils.isNotEmpty(splAttrCd)){
            qc.setSplAttrCd(splAttrCd);
        }
        if(StringUtils.isNotEmpty(isBlackList)){
            qc.setIsBlackList(Integer.valueOf(isBlackList));
        }
        if(CollectionUtils.isNotEmpty(splIds)){
            qc.setIds(splIds);
        }

        qc.setAudStsCd("2");
        qc.setBuOrgCd("00000001");
        page.setCondition(qc);
        Pager pager = this.splInfoService.searchListPage(page);
        List<SplInfoVO> list = (List<SplInfoVO>) pager.getResultList();
        ArrayList<Long> ids = new ArrayList<>();

        for (SplInfoVO vo:list) {
            ids.add(vo.getId());
            Long actLsAmt = splIdByAmtCountMap.get(vo.getId());
            if(StringUtils.isNotEmpty(actLsAmt)){
                vo.setActLsAmt(DecimalUtils.convertFenToYuan(actLsAmt));
            }
        }
        SplPropInfoQueryCondition splPropInfoQC = new SplPropInfoQueryCondition();
        splPropInfoQC.setPropTypCd("006");
        splPropInfoQC.setSplIdList(ids);
        splPropInfoQC.setIsDel(BaseConstant.IS_YESNO_NO);
        splPropInfoQC.setIsValid(BaseConstant.IS_YESNO_YES);
        List<SplPropInfoDTO> splPropInfoDTOS = this.splPropInfoApiService.getSplPropInfoList(splPropInfoQC);
        if(CollectionUtils.isNotEmpty(splPropInfoDTOS)){
            for (SplInfoVO vo:list) {
                vo.setIsVip(BaseConstant.IS_YESNO_NO_STR);
                for (SplPropInfoDTO splPropInfoDTO : splPropInfoDTOS ) {
                    if(vo.getId().equals(splPropInfoDTO.getSplId()) && StringUtils.isNotEmpty(splPropInfoDTO.getPropInfo()) && splPropInfoDTO.getPropInfo().contains("7")){
                        vo.setIsVip(BaseConstant.IS_YESNO_YES_STR);
                    }
                }
            }
        }



        //初始化供应商星级信息
        Map<String, String> starLevelMap = sysDictionaryApiService.searchGroupToMap(SplSystemConstant.SPL_SYS_CD, SplSystemConstant.DEFAULT_ORG_CD, SplRateRelInfoConstant.SPL_RATE_STAR_DIC_CD);
        StringBuilder rpcSign = new StringBuilder();
        rpcSign.append(System.currentTimeMillis()).append("_").append(CurrentThreadContext.getCurrentUserName()).append("_").append(CurrentThreadContext.getCurrentUserId());
        SplRateRelInfoQC splRateRelInfoQC = new SplRateRelInfoQC();
        splRateRelInfoQC.setDataIdList(ids);
        splRateRelInfoQC.setTabNm("SPL_BSC_INFO");
        splRateRelInfoQC.setIsNew(BaseConstant.IS_YESNO_YES);
        splRateRelInfoQC.setIsDel(BaseConstant.IS_YESNO_NO);
        splRateRelInfoQC.setIsValid(BaseConstant.IS_YESNO_YES);
        DataResultDTO resultDTO = this.splRateRelInfoQueryApiService.searchSplRateRelInfoDTOList(splRateRelInfoQC,SplSystemConstant.FL_WEB_CHL_CD, null,rpcSign.toString());
        BaseLogUtils.newWebLogger("查询供应商星级信息.DATA:"+ JSONObject.toJSONString(resultDTO)).setLogOperType(LogOperEnum.RESP)
                .setSysCd(CurrentThreadContext.getCurrentSysCd())
                .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                .setWarning(false)
                .info();
        if(BaseConstant.IS_YESNO_YES == resultDTO.getSuccess()){
            List<SplRateRelInfoDTO> splRateInfoList = (List<SplRateRelInfoDTO>)resultDTO.getData() ;
            if(CollectionUtils.isNotEmpty(splRateInfoList)){
                Map<Long,Long> splIdByStarLevelMap = new HashMap<>();
                for (SplRateRelInfoDTO rateRelDTO:splRateInfoList) {
                    splIdByStarLevelMap.put(rateRelDTO.getDataId(),rateRelDTO.getStarLevel());
                }
                for (SplInfoVO vo:list) {
                    Long levelCd = splIdByStarLevelMap.get(vo.getId());
                    if(StringUtils.isNotEmpty(levelCd)) {
                        vo.setStarLevelNm(starLevelMap.get(levelCd.toString()));
                    }
                }
            }
        }
        ListPageVO<SplInfoVO> listPage = new ListPageVO<>(list, pager.getTotalCount());
        return listPage;
    }

    @RequestMapping(value = "/toRebateRulesListPage.do",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView toRebateRulesListPage(HttpServletRequest request, HttpServletResponse response){
        ModelAndView view = new ModelAndView("product/splStepRebates/splRebateRulesList");
        List<KeyValueVO> searchBuOrgList = this.splInfoService.searchBuOrgCdList();
        view.addObject("searchBuOrgList", searchBuOrgList);
        return view ;
    }

    @RequestMapping(value = "/initRebateRulesList.do",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object initRebateRulesList(HttpServletRequest request, HttpServletResponse response){
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String splNm = request.getParameter("splNm");
        String buOrgCd = request.getParameter("buOrgCd");
        String isValid = request.getParameter("isValid");
        String crtTmStarStr = request.getParameter("crtTmStar");
        String crtTmEndStr = request.getParameter("crtTmEnd");
        String offectTmStarStr = request.getParameter("offectTmStar");
        String offectTmEndStr = request.getParameter("offectTmEnd");
        String efficacyTmStarStr = request.getParameter("efficacyTmStar");
        String efficacyTmEndStr = request.getParameter("efficacyTmEnd");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        SplStepRebatesInfoQC qc = new SplStepRebatesInfoQC();
        if(StringUtils.isNotEmpty(splNm)){
            qc.setSplNm(splNm);
        }
        if(StringUtils.isNotEmpty(isValid)){
            qc.setIsValid(Integer.valueOf(isValid));
        }
        if(StringUtils.isNotEmpty(crtTmStarStr)){
            qc.setCrtTmStar(crtTmStarStr);
        }
        if(StringUtils.isNotEmpty(crtTmEndStr)){
            qc.setCrtTmEnd(crtTmEndStr);
        }
        if(StringUtils.isNotEmpty(offectTmStarStr)){
            qc.setOffectTmStar(offectTmStarStr);
        }
        if(StringUtils.isNotEmpty(offectTmEndStr)){
            qc.setOffectTmEnd(offectTmEndStr);
        }
        if(StringUtils.isNotEmpty(efficacyTmStarStr)){
            qc.setEfficacyTmStar(efficacyTmStarStr);
        }
        if(StringUtils.isNotEmpty(efficacyTmEndStr)){
            qc.setEfficacyTmEnd(efficacyTmEndStr);
        }
        if(StringUtils.isNotEmpty(buOrgCd)){
            qc.setBuOrgCd(buOrgCd);
        }
        page.setCondition(qc);
        Pager pager = this.splStepRebatesService.searchListPage(page);
        List<SplStepRebatesInfoDTO> list = (List<SplStepRebatesInfoDTO>)pager.getResultList();
        ListPageVO<SplStepRebatesVO> listPage = new ListPageVO<>(SplStepRebatesVOTransform.toVOList(list), pager.getTotalCount());
        return listPage;
    }

    @RequestMapping(value = "/toAddPage.do",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response){
        ModelAndView view = new ModelAndView("product/splStepRebates/addRebatesPage");
        String splId = request.getParameter("splId");
        String splNm = request.getParameter("splNm");
        String isVip = request.getParameter("isVip");
        view.addObject("splId",splId);
        view.addObject("splNm",splNm);
        view.addObject("isVip",isVip);
        view.addObject("crtUsrNm",CurrentThreadContext.getCurrentUserName());
        view.addObject("crtUsrId",CurrentThreadContext.getCurrentUserId());
        return view;
    }

    @RequestMapping(value = "/toModifyPage.do",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response){
        ModelAndView view = new ModelAndView("product/splStepRebates/addRebatesPage");
        String id = request.getParameter("id");
        view.addObject("id",id);
        return view;
    }

    @RequestMapping(value = "/getById.do",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response){
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"获取成功");
        String id = request.getParameter("id");

        SplStepRebatesVO vo = this.splStepRebatesService.getVOById(Long.valueOf(id));
        result.setData(vo);
        return result ;
    }


    @RequestMapping(value = "/add.do",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response){
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"新增成功");
        try {
            SplStepRebatesVO vo = this.getAddParaters(request,new SplStepRebatesVO());
            Long id = this.splStepRebatesService.add(vo);
            if(StringUtils.isEmpty(id)){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("新增失败");
            }
        }catch (BaseException be){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(be.getMessage());
        }catch (Exception ex){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        }

        return result;
    }

    @RequestMapping(value = "/modify.do",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response){
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"修改成功");
        try {
            SplStepRebatesVO vo = this.getModifyParaters(request,new SplStepRebatesVO());
            String id = request.getParameter("id");
            vo.setId(Long.valueOf(id));
            boolean b = this.splStepRebatesService.modufy(vo);
            if(!b){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败！");
            }
        }catch (BaseException be){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(be.getMessage());
        }catch (Exception ex){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        }

        return result;
    }

    @RequestMapping(value = "/modifyIsvalid.do",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object modifyIsvalid(HttpServletRequest request, HttpServletResponse response){
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"修改成功");
        try {
            String id = request.getParameter("id");
            SplStepRebatesVO vo = new SplStepRebatesVO();
            vo.setId(Long.valueOf(id));
            vo.setIsValid(BaseConstant.IS_YESNO_NO);
            vo.setIsDel(BaseConstant.IS_YESNO_YES);
            boolean b = this.splStepRebatesService.modufy(vo);
            if(!b){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败！");
            }
        }catch (BaseException be){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(be.getMessage());
        }catch (Exception ex){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        }

        return result;
    }
@RequestMapping(value = "/checkOnly.do",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object checkOnly(HttpServletRequest request, HttpServletResponse response){
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"成功");
        try {
            String id = request.getParameter("id");
            String splId = request.getParameter("splId");
            String splNm = request.getParameter("splNm");
            String isVipWork = request.getParameter("isVipWork");
            if(StringUtils.isEmpty(splId)){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("供应商id不能为空！");
                return result;
            }
            if(StringUtils.isEmpty(isVipWork)){
                isVipWork = BaseConstant.IS_YESNO_NO_STR;
            }
            SplStepRebatesInfoQC condition = new SplStepRebatesInfoQC();
            condition.setIsDel(BaseConstant.IS_YESNO_NO);
            condition.setIsValid(BaseConstant.IS_YESNO_YES);
            condition.setIsVipWork(Integer.valueOf(isVipWork));
            condition.setSplId(Long.valueOf(splId));
            List<SplStepRebatesVO> voList = this.splStepRebatesService.searchList(condition);
            if(StringUtils.isNotEmpty(id) && CollectionUtils.isNotEmpty(voList)){
                boolean b = true ;
                for (SplStepRebatesVO vo:voList) {
                    if(!vo.getId().equals(Long.valueOf(id))){
                        b = false ;
                        break;
                    }
                }
                if(!b) {
                    if(BaseConstant.IS_YESNO_YES_STR.equals(isVipWork)){
                        result.setInfo("供应商【"+splNm+"】存在生效大客户业务阶梯返利规则，需将原规则禁用后生效");
                    }else{
                        result.setInfo("供应商【"+splNm+"】存在生效阶梯返利规则，需将原规则禁用后生效");
                    }
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                }

            }else {
                if (CollectionUtils.isNotEmpty(voList)) {
                    if(BaseConstant.IS_YESNO_YES_STR.equals(isVipWork)){
                        result.setInfo("供应商【"+splNm+"】存在生效大客户业务阶梯返利规则，需将原规则禁用后生效");
                    }else{
                        result.setInfo("供应商【"+splNm+"】存在生效阶梯返利规则，需将原规则禁用后生效");
                    }
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                }
            }
        }catch (BaseException be){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(be.getMessage());
        }catch (Exception ex){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        }

        return result;
    }

    private SplStepRebatesVO getAddParaters(HttpServletRequest request,SplStepRebatesVO vo){
        this.getParaters(request,vo);
        vo.setCrtTm(new Date());
        vo.setIsDel(BaseConstant.IS_YESNO_NO);
        vo.setIsNew(BaseConstant.IS_YESNO_YES);
        return vo ;

    }
    private SplStepRebatesVO getModifyParaters(HttpServletRequest request,SplStepRebatesVO vo){
        this.getParaters(request,vo);
        vo.setMdfTm(new Date());
        vo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        vo.setMdfUsrNm(CurrentThreadContext.getCurrentUserName());
        return vo ;
    }

    private SplStepRebatesVO getParaters(HttpServletRequest request,SplStepRebatesVO vo){
        if(vo == null){
            vo = new SplStepRebatesVO();
        }
        String starStr = " 00:00:00";
        String endStr = " 23:59:59";
        String stepNum = request.getParameter("stepNum");
        String starAmt_1 = request.getParameter("starAmt_1");
        String starAmt_2 = request.getParameter("starAmt_2");
        String starAmt_3 = request.getParameter("starAmt_3");
        String starAmt_4 = request.getParameter("starAmt_4");
        String endAmt_1 = request.getParameter("endAmt_1");
        String endAmt_2 = request.getParameter("endAmt_2");
        String endAmt_3 = request.getParameter("endAmt_3");
        String endAmt_4 = request.getParameter("endAmt_4");
        String rate_1 = request.getParameter("rate_1");
        String rate_2 = request.getParameter("rate_2");
        String rate_3 = request.getParameter("rate_3");
        String rate_4 = request.getParameter("rate_4");
        String prjStarTmStr = request.getParameter("prjStarTm");
        String prjEndTmStr = request.getParameter("prjEndTm");
        String indateStarStr = request.getParameter("indateStar");
        String indateEndStr = request.getParameter("indateEnd");
        String crtUsrId = request.getParameter("crtUsrId");
        String crtUsrNm = request.getParameter("crtUsrNm");
        String stepRem = request.getParameter("stepRem");
        String splId = request.getParameter("splId");
        String splNm = request.getParameter("splNm");
        String isVipWork = request.getParameter("isVipWork");
        if(StringUtils.isBlank(splId)){
            throw new BaseException(BaseExceptionConstant.COMMON_0001,"供应商ID不能为空！");
        }
        if(StringUtils.isBlank(isVipWork)){
            throw new BaseException(BaseExceptionConstant.COMMON_0001,"是否大客户业务政策不能为空！");
        }

        if(StringUtils.isBlank(stepNum)){
            throw new BaseException(BaseExceptionConstant.COMMON_0001,"阶梯数不能为空！");
        }
        if("2".equals(stepNum) && !endAmt_1.equals(starAmt_2)) {
            throw new BaseException(BaseExceptionConstant.COMMON_0001,"阶梯区间需连续！");
        }
        if("3".equals(stepNum) && (!endAmt_1.equals(starAmt_2) || !endAmt_2.equals(starAmt_3))) {
            throw new BaseException(BaseExceptionConstant.COMMON_0001,"阶梯区间需连续！");
        }
        if("4".equals(stepNum) && (!endAmt_1.equals(starAmt_2) || !endAmt_2.equals(starAmt_3) ||!endAmt_3.equals(starAmt_4))) {
            throw new BaseException(BaseExceptionConstant.COMMON_0001,"阶梯区间需连续！");
        }
        if(StringUtils.isNotEmpty(rate_1)){
            if(Double.valueOf(rate_1) >5 ){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"返利比例不能超过5%！");
            }
            if(Double.valueOf(rate_1)<0){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"返利比例不得为负！");
            }

        }
        if(StringUtils.isNotEmpty(rate_2)){
            if(Double.valueOf(rate_2) >5 ){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"返利比例不能超过5%！");
            }
            if(Double.valueOf(rate_2)<0){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"返利比例不得为负！");
            }

        }
        if(StringUtils.isNotEmpty(rate_3)){
            if(Double.valueOf(rate_3) >5 ){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"返利比例不能超过5%！");
            }
            if(Double.valueOf(rate_3)<0){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"返利比例不得为负！");
            }

        }
        if(StringUtils.isNotEmpty(rate_4)){
            if(Double.valueOf(rate_4) >5 ){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"返利比例不能超过5%！");
            }
            if(Double.valueOf(rate_4)<0){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"返利比例不得为负！");
            }

        }
        if(StringUtils.isNotEmpty(prjStarTmStr) && StringUtils.isNotEmpty(prjEndTmStr)){
            Date prjStarTm = DateUtils.formatStringToDate(prjStarTmStr + starStr ,DateUtils.YYYY_MM_DDHHMMSS);
            Date prjEndTm = DateUtils.formatStringToDate(prjEndTmStr + endStr ,DateUtils.YYYY_MM_DDHHMMSS);
            if(prjStarTm.after(prjEndTm)){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"可申请阶梯返利项目范围前后时间有误！");
            }
            if(prjEndTm.after(DateUtils.getDateAddDate(prjStarTm,DateUtils.MONTH,12))){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"可申请阶梯返利项目范围最大值为12个月！");
            }
            vo.setPrjStarTm(prjStarTm);
            vo.setPrjEndTm(prjEndTm);
        }

        if(StringUtils.isNotEmpty(indateStarStr) && StringUtils.isNotEmpty(indateEndStr)){
            Date indateStar = DateUtils.formatStringToDate(indateStarStr + starStr ,DateUtils.YYYY_MM_DDHHMMSS);
            Date indateEnd = DateUtils.formatStringToDate(indateEndStr + endStr ,DateUtils.YYYY_MM_DDHHMMSS);
            if(indateStar.after(indateEnd)){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"有效期前后时间有误！");
            }
            if(indateEnd.after(DateUtils.getDateAddDate(indateStar,DateUtils.MONTH,12))){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"有效期范围最大值为12个月！");
            }
            vo.setIndateStar(indateStar);
            vo.setIndateEnd(indateEnd);
            if(new Date().after(vo.getIndateEnd())){
                vo.setIsValid(BaseConstant.IS_YESNO_NO);
            }else{
                vo.setIsValid(BaseConstant.IS_YESNO_YES);
            }
        }



        if(StringUtils.isNotEmpty(starAmt_1) && StringUtils.isNotEmpty(endAmt_1)){
            if(Double.valueOf(starAmt_1) >= Double.valueOf(endAmt_1)){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"一阶段返利金额区间有误，阶梯区间需连续！");
            }
        }
        if(StringUtils.isNotEmpty(starAmt_2) && StringUtils.isNotEmpty(endAmt_2)){
            if(Double.valueOf(starAmt_2) >= Double.valueOf(endAmt_2)){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"二阶段返利金额区间有误，阶梯区间需连续！");
            }
        }
        if(StringUtils.isNotEmpty(starAmt_3) && StringUtils.isNotEmpty(endAmt_3)){
            if(Double.valueOf(starAmt_3) >= Double.valueOf(endAmt_3)){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"三阶段返利金额区间有误，阶梯区间需连续！");
            }
        }
        if(StringUtils.isNotEmpty(starAmt_4) && StringUtils.isNotEmpty(endAmt_4)){
            if(Double.valueOf(starAmt_4) >= Double.valueOf(endAmt_4)){
                throw new BaseException(BaseExceptionConstant.COMMON_0001,"四阶段返利金额区间有误，阶梯区间需连续！");
            }
        }
        if(StringUtils.isNotEmpty(stepRem) && stepRem.length() >300){
            throw new BaseException(BaseExceptionConstant.COMMON_0001,"备注信息最大长度为300！");
        }

        vo.setSplId(Long.valueOf(splId));
        vo.setSplNm(splNm);
        vo.setIsVipWork(Integer.valueOf(isVipWork));
        vo.setStepNum(Long.valueOf(stepNum));
        vo.setStepRem(stepRem);
        if(StringUtils.isNotEmpty(crtUsrId)) {
            vo.setCrtUsrId(Long.valueOf(crtUsrId));
        }
        vo.setCrtUsrNm(crtUsrNm);
        List<StepRebatesDetailVO> detailList = new ArrayList<>();
        BigDecimal b = new BigDecimal(10000L);
        for (int i = 1; i <= Integer.valueOf(stepNum);i++){
            StepRebatesDetailVO detailVO = null ;

            if(i == 1){
                detailVO = new StepRebatesDetailVO();
                Double amtStar = DecimalUtils.mul(Double.valueOf(starAmt_1),1000000.00);
                Double amtEnd = DecimalUtils.mul(Double.valueOf(endAmt_1),1000000.00);
                detailVO.setStarAmt(amtStar.longValue());
                detailVO.setEndAmt(amtEnd.longValue());
                detailVO.setRate(DecimalUtils.cut(Double.valueOf(rate_1),2));
                detailVO.setStep(i);
                detailVO.setIsDel(BaseConstant.IS_YESNO_NO);

            }
            if(i == 2){
                detailVO = new StepRebatesDetailVO();
                Double amtStar = DecimalUtils.mul(Double.valueOf(starAmt_2),1000000.00);
                Double amtEnd = DecimalUtils.mul(Double.valueOf(endAmt_2),1000000.00);
                detailVO.setStarAmt(amtStar.longValue());
                detailVO.setEndAmt(amtEnd.longValue());
                detailVO.setRate(DecimalUtils.cut(Double.valueOf(rate_2),2));
                detailVO.setStep(i);
                detailVO.setIsDel(BaseConstant.IS_YESNO_NO);

            }
            if(i == 3){
                detailVO = new StepRebatesDetailVO();
                Double amtStar = DecimalUtils.mul(Double.valueOf(starAmt_3),1000000.00);
                Double amtEnd = DecimalUtils.mul(Double.valueOf(endAmt_3),1000000.00);
                detailVO.setStarAmt(amtStar.longValue());
                detailVO.setEndAmt(amtEnd.longValue());
                detailVO.setRate(DecimalUtils.cut(Double.valueOf(rate_3),2));
                detailVO.setStep(i);
                detailVO.setIsDel(BaseConstant.IS_YESNO_NO);

            }
            if(i == 4){
                detailVO = new StepRebatesDetailVO();
                Double amtStar = DecimalUtils.mul(Double.valueOf(starAmt_4),1000000.00);
                Double amtEnd = DecimalUtils.mul(Double.valueOf(endAmt_4),1000000.00);
                detailVO.setStarAmt(amtStar.longValue());
                detailVO.setEndAmt(amtEnd.longValue());
                detailVO.setRate(DecimalUtils.cut(Double.valueOf(rate_4),2));
                detailVO.setStep(i);
                detailVO.setIsDel(BaseConstant.IS_YESNO_NO);

            }
            if(detailVO != null) {
                detailList.add(detailVO);
            }
        }
        vo.setDetailVOList(detailList);
        return vo ;
    }

    @RequestMapping(value = "/toRebateRecord.do",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView toRebateRecord(HttpServletRequest request, HttpServletResponse response){
        ModelAndView view = new ModelAndView("product/splStepRebates/rebateRecordListPage");
        List<KeyValueVO> searchBuOrgList = this.splInfoService.searchBuOrgCdList();
        view.addObject("searchBuOrgList", searchBuOrgList);
        return view ;
    }

    @RequestMapping(value = "/initRebateRecord.do",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object initRebateRecord(HttpServletRequest request, HttpServletResponse response){
        String crtUsrName = request.getParameter("crtUsrName");
        String crtTmStr = request.getParameter("crtTm");
        String applyState = request.getParameter("applyState");
        String buOrgCd = request.getParameter("buOrgCd");
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        PrjStepRebateFeeQC qc = new PrjStepRebateFeeQC();
        if(StringUtils.isNotEmpty(crtUsrName)){
            qc.setCrtUsrName(crtUsrName);
        }
        if(StringUtils.isNotEmpty(crtTmStr)){
            qc.setCrtTm(DateUtils.formatStringToDate(crtTmStr,DateUtils.YYYY_MM_DD));
        }
        if(StringUtils.isNotEmpty(applyState)){
            qc.setApplyState(applyState);
        }
        if(StringUtils.isNotEmpty(buOrgCd)){
            qc.setBuOrgCd(buOrgCd);
        }
        page.setCondition(qc);
        BaseLogUtils.newWebLogger("查询返利列表").setLogOperType(LogOperEnum.RESP)
                .setSysCd(CurrentThreadContext.getCurrentSysCd())
                .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                .setKeys("qc",JSON.toJSONString(page))
                .setWarning(false)
                .info();
        Pager pager= prjStepRebateApiService.getStepRebateFeeListPage(page);
        List<PrjStepRebateFeeDTO> dtoList = (List<PrjStepRebateFeeDTO> )pager.getResultList();
        if(CollectionUtils.isNotEmpty(dtoList)){
            List<PrjStepRebateFeeVO> voList = PrjStepRebateFeeVOTransform.toVOList(dtoList);
            ListPageVO<PrjStepRebateFeeVO> listPage = new ListPageVO<>(voList, pager.getTotalCount());
            return listPage;
        }else{
            return  new ListPageVO<>(new ArrayList<>(),0);
        }
    }

    private int getMonth(Date starDt,Date endDt){
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(starDt);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDt);
        Calendar temp = Calendar.getInstance();
        temp.setTime(endDt);
        temp.add(Calendar.DATE, 1);

        int month = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
        if(month <0){
            month +=12 ;
        }
        return month ;
    }

}
